<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2020-08-01
 * Time: 下午 08:38
 */
namespace Action\Page;

use Action\Common\BaseLayout;
use Model\Page;

/**
 * Class Edit
 * @property-read \Model\Page $pageModel
 * @package Action\Page
 */
class Save extends BaseLayout {
    public function main() {
        $post = $_POST;
        $id = $post['id'];
        $template = $post['template'];

        $this->setMessageData($post);
        
        if(empty($template)) {
            $this->setMessage("缺少模板");
            $this->jsBack();
        }
        
        $templateInfo = $this->pageModel->getTemplateInfo($template);
        
        if(empty($templateInfo)) {
            $this->setMessage("模板 '$template' 已经不存在了");
            $this->jsBack();
        }
        
        if(!$id) {
            if($this->pageModel->exists($id)) {
                $this->setMessage("页面 $id 已经存在");
                $this->jsBack();
            }
            
            $idCount = 1;
            
            do {
                $id = base_convert($idCount.date('YmdH'), 10, 32);
                $idCount ++;
            } while($this->pageModel->exists($id));
        }
        
        $this->pageModel->save($id, [
            'name' => $post['name'],
            'ver' => time(),
            'desc' => $post['desc'],
            'enabled' => $post['enabled'],
            'template' => $post['template'],
            'data' => $post['data']
        ]);
        
        $this->jsBackAlert('保存成功');
    }
    
    // protected function _checkParams($data, $templateParams) {
    //     foreach ($templateParams as $key => $val) {
    //         $label = $val['label'] ? $val['label'] : $key;
    //        
    //         if($val['required'] && empty($data[$key])) {
    //             $this->setMessage("$label 不能为空");
    //             $this->jsBack();
    //         }
    //        
    //         if($val['type'] == Page::PT_LIST) {
    //             foreach ((array)$val['children_params'] as $ck => $cv) {
    //                
    //             }
    //         }
    //     }
    // }
} 